package com.cwz.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwz.api.entity.SysJobLog;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.quartz.mapper.SysJobLogMapper;
import com.cwz.quartz.model.SysJobLogVo;
import com.cwz.quartz.service.SysJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 定时任务调度日志表 服务实现类
 * </p>
 *
 * @author Wen
 * @since 2023-08-24
 */
@Service
public class SysJobLogServiceImpl extends ServiceImpl<SysJobLogMapper, SysJobLog> implements SysJobLogService {
	@Autowired
	private SysJobLogMapper sysJobLogMapper;

	@Override
	public Map<String, Object> selectJobLogList(SysJobLogVo jobLog) {
		Page<SysJobLog> page = this.sysJobLogMapper.selectPage(
			new Page<>(jobLog.getPageNum(), jobLog.getPagSize()),
			new QueryWrapper<SysJobLog>()
				.like(StringUtils.isNotBlank(jobLog.getJobName()), "job_name", jobLog.getJobName())
				.eq(StringUtils.isNotBlank(jobLog.getJobGroup()), "job_group", jobLog.getJobGroup())
				.eq(StringUtils.isNotBlank(jobLog.getStatus()), "status", jobLog.getStatus())
				.like(StringUtils.isNotBlank(jobLog.getInvokeTarget()), "invoke_target", jobLog.getInvokeTarget())
				.apply(StringUtils.isNotNull(jobLog.getStartTime()),
					"date_format(create_time,'%Y-%m-%d') >= date_format({0},'%Y-%m-%d')", jobLog.getStartTime())
				.apply(StringUtils.isNotNull(jobLog.getStopTime()),
					"date_format(create_time,'%Y-%m-%d') <= date_format({0},'%Y-%m-%d')", jobLog.getStopTime())
		);
		Map<String, Object> map = new HashMap<>();
		map.put("list", page.getRecords());
		map.put("total", page.getTotal());
		return map;
	}

	@Override
	public SysJobLog selectJobLogById(Long jobLogId) {
		return this.sysJobLogMapper.selectById(jobLogId);
	}

	@Override
	public void addJobLog(SysJobLog jobLog) {
		this.sysJobLogMapper.insert(jobLog);
	}

	@Override
	public int deleteJobLogByIds(Long[] logIds) {
		return this.sysJobLogMapper.delete(new QueryWrapper<SysJobLog>()
			.in("job_log_id", logIds));
	}

	@Override
	public int deleteJobLogById(Long jobId) {
		return this.sysJobLogMapper.deleteById(jobId);
	}

	@Override
	public void cleanJobLog() {
		this.sysJobLogMapper.cleanJobLog();
	}
}
